import os
import sys
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class ProjectListWidget(QListWidget):
    project_Signal=pyqtSignal(dict)
    def __init__(self):
        super(ProjectListWidget, self).__init__()
        self.itemClicked.connect(self.show_data)

    def set_data(self,data):
        self.clear()
        for k,v in data.items():
            current_data={}
            name=k
            current_data[k]=v
            item=QListWidgetItem()
            item.setBackground(QBrush(QColor(v['color'])))
            item.setText(name)
            item.setData(5,v)
            item.setTextAlignment(Qt.AlignCenter)
            self.addItem(item)

    def show_data(self,item):
        data=item.data(5)
        print('select data:',data)
        self.project_Signal.emit(data)


class CGTWprojectInfo(QDialog):

    def __init__(self):
        super(CGTWprojectInfo, self).__init__()
        self.main_layout=QHBoxLayout()
        self.left_list=ProjectListWidget()
        self.right_layout=QVBoxLayout()
        self.right_label_layout=QHBoxLayout()
        self.right_label=QLabel('cgtw项目信息')
        # self.

    # def


class ProjControl(QWidget):

    def __init__(self):
        super(ProjControl, self).__init__()
        self.project=''  #当前选择的项目 eg: XXSS
        self.project_color=''  #当前选择的项目的颜色
        self.project_info_path=''  #当前项目信息路径
        self.btn_style= """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                  QPushButton{background-color:#FFDEAD}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.big_logo_font=QFont('',25,55)
        self.mid_logo_font=QFont('',15,50)
        #self.data=self.getData()
        self.setWindowTitle("项目配置")
        self.icon = QIcon()
        self.icon_path= os.path.join(os.path.dirname(__file__),'icon.png')
        self.img_path=os.path.join(os.path.dirname(__file__),'houdini.png')
        self.icon.addPixmap(QPixmap( self.img_path))
        self.setWindowIcon(self.icon)
        self.main_layout=QVBoxLayout()
        self.label_layout=QHBoxLayout()
        self.img_label=QLabel()
        self.img_label.setPixmap(QPixmap(self.img_path))
        self.show_label=QLabel('项目配置预设')
        self.label_layout.addWidget(self.img_label)
        self.label_layout.addWidget(self.show_label)

        self.hSplitter = QSplitter(Qt.Horizontal)
        self.left_frame=QFrame()
        self.left_frame.setStyleSheet("QFrame{background-color:#DCDCDC}")
        self.left_frame_layout=QVBoxLayout()
        self.glob_config_layout=QHBoxLayout()
        self.glob_path_btn=QPushButton('项目配置路径:')
        self.glob_path_btn.clicked.connect(self._get_glob_path)
        self.glob_path_btn.setStyleSheet(self.btn_style)
        self.glob_edit=QLineEdit()
        # self.glob_edit.setText(r"")
        self.glob_config_btn=QPushButton('获取项目信息')
        self.glob_config_btn.clicked.connect(self._get_glob_info)
        # self.glob_config_layout.addWidget(self.glob_path_btn)
        # self.glob_config_layout.addWidget(self.glob_edit)
        self.glob_config_layout.addWidget(self.glob_config_btn)
        self.glob_config_btn.setStyleSheet(self.btn_style)
        self.init_glob_edit()
        self.project_list=ProjectListWidget()
        self.project_list.project_Signal.connect(self.show_project_info)
        self.left_frame_layout.addLayout(self.glob_config_layout)
        self.left_frame_layout.addWidget(self.project_list)
        self.left_frame.setLayout(self.left_frame_layout)
        self.hSplitter.addWidget(self.left_frame)

        self.right_frame=QFrame()
        self.right_layout=QVBoxLayout()
        self.right_layout.setAlignment(Qt.AlignTop|Qt.AlignCenter)
        self.right_layout.setSpacing(15)
        self.right_label=QLabel('项目信息')
        self.right_label.setFont(self.big_logo_font)
        self.right_label.setAlignment(Qt.AlignCenter)
        self.project_info_layout=QHBoxLayout()
        # self.project_info_layout.setAlignment(Qt.AlignCenter)
        self.project_name_label=QLabel('项目名:')
        self.project_name_edit=QLineEdit()
        # self.project_name_edit.setFont(self.mid_logo_font)

        self.project_entity_label=QLabel('项目简称:')
        self.project_entity_edit=QLineEdit()
        self.project_info_layout.addWidget(self.project_name_label)
        self.project_info_layout.addWidget(self.project_name_edit)
        self.project_info_layout.addWidget(self.project_entity_label)
        self.project_info_layout.addWidget(self.project_entity_edit)
        self.frame_layout=QHBoxLayout()
        self.frame_layout.setContentsMargins(0,10,180,10)
        self.frame_label=QLabel('FPS:')
        self.frame_edit=QLineEdit()
        self.frame_edit.setMaximumWidth(100)
        self.frame_edit.setAlignment(Qt.AlignLeft)
        self.color_label=QLabel('项目颜色:')
        self.color_edit=QLineEdit()
        self.frame_layout.addWidget(self.frame_label)
        self.frame_layout.addWidget(self.frame_edit)
        self.frame_layout.addWidget(self.color_label)
        self.frame_layout.addWidget(self.color_edit)
        self.resolution_layout=QHBoxLayout()
        self.resolution_label=QLabel('分辨率:')
        self.resolution_x_edit=QLineEdit()
        self.resolution_y_edit=QLineEdit()
        self.pre_resolution_comb=QComboBox()
        self.pre_resolution_comb.currentTextChanged.connect(self._change_resolution)
        self.init_pre_resolution()
        self.resolution_layout.addWidget(self.resolution_label)
        self.resolution_layout.addWidget(self.resolution_x_edit)
        self.resolution_layout.addWidget(self.resolution_y_edit)
        self.resolution_layout.addWidget(self.pre_resolution_comb)
        self.cgtw_path_layout=QHBoxLayout()
        self.cgtw_path_label=QLabel('项目路径:  ')
        self.cgtw_path_edit=QLineEdit()
        self.cgtw_path_btn=QPushButton('...')
        self.cgtw_path_btn.clicked.connect(self._choose_file)
        self.cgtw_path_btn.setStyleSheet(self.btn_style)
        self.cgtw_path_layout.addWidget(self.cgtw_path_label)
        self.cgtw_path_layout.addWidget(self.cgtw_path_edit)
        self.cgtw_path_layout.addWidget(self.cgtw_path_btn)
        self.cgtw_path_layout.setContentsMargins(0,10,0,50)
        self.save_btn=QPushButton('保存配置')
        self.save_btn.clicked.connect(self._save_config)
        self.save_btn.setMinimumHeight(50)
        self.show_project_info_layout=QHBoxLayout()
        self.show_project_info_layout.setAlignment(Qt.AlignRight)
        self.show_project_btn=QPushButton('显示cgtw信息')
        self.show_project_btn.setStyleSheet(self.btn_style)
        self.show_project_btn.clicked.connect(self._show_cgtw_project_info)
        self.show_project_info_layout.addWidget(self.show_project_btn)
        self.right_layout.addWidget(self.right_label)
        self.right_layout.addLayout(self.project_info_layout)
        self.right_layout.addLayout(self.frame_layout)
        self.right_layout.addLayout(self.resolution_layout)
        self.right_layout.addLayout(self.cgtw_path_layout)
        self.right_layout.addWidget(self.save_btn)
        self.right_layout.addLayout(self.show_project_info_layout)
        self.right_frame.setLayout(self.right_layout)
        self.hSplitter.addWidget(self.right_frame)

        self.hSplitter.setSizes([100,300])
        self.main_layout.addWidget(self.hSplitter)
        self.setLayout(self.main_layout)

    def init_connect(self):
        try:
            time_connect = psycopg2.connect(database='houdini',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
        except Exception as cgdb_err:
            print(str(cgdb_err))

            return None, None
        return time_connect, time_cursor

    def init_glob_edit(self):
        config_path=''
        control_cfg_path = os.path.join(os.path.dirname(__file__),'control_cfg')
        if os.path.exists(control_cfg_path):
            with open(control_cfg_path,'r',encoding='utf8') as r:
                config_path=r.read()

        self.glob_edit.setText(config_path)

    def init_pre_resolution(self):
        resolution_list=['3840x2160','2048x1152','1920x1080','1280x720']
        self.pre_resolution_comb.addItems(resolution_list)

    def _get_glob_path(self):
        """
        打开项目目录
        :return:
        """
        # fileName = QFileDialog.getSaveFileName(None,'输出文件','','Excel files(*.xlsx , *.xls)')
        # print(fileName[0])
        dir = QFileDialog.getExistingDirectory(self, '选择目录')
        self.glob_edit.setText(dir)


    def _get_glob_info(self):
        """
        从指定路径中读取项目配置信息
        :return:
        """
        try:
            projects_data={}
            time_connect, time_cursor = self.init_connect()
            sql="select fps,color,resolution,path,fullname,entityname from projectconfig"
            try:
                time_cursor.execute(sql)
                result = time_cursor.fetchall()
                if result:
                    for i in result:
                        data = {}
                        data['fps']=i[0]
                        data['color']=i[1]
                        data['resolution']=i[2]
                        data['path']=i[3]
                        data['fullname']=i[4]
                        data['entityname']=i[5]
                        projects_data[data['entityname']]=data
            except Exception as _get_glob_info_ERR:
                print(str(_get_glob_info_ERR))
            finally:
                time_connect.close()
            if projects_data:
                self.project_list.set_data(projects_data)
        except Exception as _get_glob_info_ERR:
            print(str(_get_glob_info_ERR))

    def _change_resolution(self,resolution):
        x, y = resolution.split('x')
        self.resolution_x_edit.setText(x)
        self.resolution_y_edit.setText(y)

    def show_project_info(self,data):
        if data:
            self.project_name_edit.setText(data['fullname'])
            self.project_entity_edit.setText(data['entityname'])
            self.frame_edit.setText(data['fps'])
            self.color_edit.setText(data['color'])
            resolution=data['resolution']
            if resolution:
                x,y=resolution.split('x')
                self.resolution_x_edit.setText(x)
                self.resolution_y_edit.setText(y)
            else:
                self.resolution_x_edit.setText('')
                self.resolution_y_edit.setText('')
            self.cgtw_path_edit.setText(data['path'])
            # project=data['entityname']
            # self.project=project
            # prject_name=value[0]
            # self.project_color =value[1]
            # fps=value[2]
            # resolution=value[3]
            # path=value[4] if value[4] else ''
            # self.project_name_edit.setText(prject_name)
            # self.color_edit.setText(value[1])
            # self.frame_edit.setText(str(fps))
            # self.cgtw_path_edit.setText(path)


    def _choose_file(self):
        """
        选择目录
        :return:
        """
        dir = QFileDialog.getExistingDirectory(self, '选择目录')
        if dir:
            r_dir=dir.replace('/','\\')
            self.cgtw_path_edit.setText(r_dir)

    def _show_cgtw_project_info(self):
        """
        打开排期系统里数据库里的项目信息
        :return:
        """
        # QMessageBox.information(self,'获取信息','直接从排期软件上输出一个项目的信息文本吧')
        time_connect, time_cursor = self.init_connect()
        sql="select fps,color,resolution,path,fullname,entityname from projectconfig where entityname = '{}'".format(self.project_entity_edit.text())
        try:
            time_cursor.execute(sql)
            result=time_cursor.fetchone()
            if result:
                print(result)
        except Exception as get_path_ERR:
            print(str(get_path_ERR))
        finally:
            time_connect.close()

    def _save_config(self):
        # project_info={}

        # if self.project and self.project_info_path:
        project_name=self.project_name_edit.text()
        entity_name=self.project_entity_edit.text()
        color=self.color_edit.text()
        fps=self.frame_edit.text()
        x=self.resolution_x_edit.text()
        y=self.resolution_y_edit.text()
        resolution=x+'x'+y
        cgtw_path = self.cgtw_path_edit.text()
        # with open(self.project_info_path,'r',encoding='utf8') as r:
        #     project_info=eval(r.read())
        # if project_info:
        #     project_info[self.project]=[project_name,self.project_color,int(fps),resolution,cgtw_path]
            # with open(self.project_info_path,'w',encoding='utf8') as w:
            #     w.write(str(project_info))
        if entity_name:
            sql="insert into projectconfig(fps,color,resolution,path,fullname,entityname) values('{0}','{1}','{2}','{3}','{4}','{5}') on conflict(entityname)" \
                "do update set fps ='{0}',color='{1}',resolution='{2}',path='{3}',fullname='{4}'".format(fps,color,resolution,cgtw_path,project_name,entity_name)

            time_connect, time_cursor = self.init_connect()
            try:
                time_cursor.execute(sql)
                time_connect.commit()
            except Exception as _save_config_ERR:
                print(str(_save_config_ERR))
                QMessageBox.information(self, '保存', str(_save_config_ERR))
            finally:
                time_connect.close()

            self._get_glob_info() #重新刷新项目列表

        else:
            QMessageBox.information(self, '保存', '请输入项目简称')




if __name__ == '__main__':
    app=QApplication(sys.argv)
    p=ProjControl()
    p.show()
    sys.exit(app.exec_())